package freemaker;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 
 * <b>
 *    FreeMarkerUtil 模板工具
 * </b>
 * @author kangxu
 *
 */
public class FreeMarkerUtil {
    
    /**
     * 
     * TODO
     * <br>
     * @author kangxu2 2016-11-23
     *
     * @param fltFile  flt文件名
     * @param templatePath flt文件路径   src/template
     * @param datas 数据集合
     * @return
     */
    public static String geneFileStr(String fltFile,String templatePath,Map<String, Object> datas){
        
        Configuration cfg = new Configuration();
        try {
            cfg.setDirectoryForTemplateLoading(new File(templatePath));
            Template template = cfg.getTemplate(fltFile);
//            StringWriter out = new StringWriter();  
            
            Writer out  = new OutputStreamWriter(new FileOutputStream("success.html"),"UTF-8");  
            template.process(datas, out);  
            out.flush();
            out.close();
            return null;
            
            
        } catch (Exception e) {
            e.printStackTrace();
        } 
        
        return null;
        
    }
    
    
    public  static  String  getTemplateContent(String content,Map<String, Object> datas){
    	String result="";
    	Configuration cfg = new Configuration();  
        StringTemplateLoader stringLoader = new StringTemplateLoader();  
        stringLoader.putTemplate("myTemplate",content);  
        cfg.setTemplateLoader(stringLoader);  
        try {  
            Template template = cfg.getTemplate("myTemplate","utf-8");  
           
            StringWriter writer = new StringWriter();    
                template.process(datas, writer);  
                result=writer.toString();    
              
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    	
    	return result;
    }
 
}